package xkp.lesson1;

import org.junit.Test;

import java.sql.*;
import java.util.List;

public class TestJDBC {
    //使用预处理对象彻底解决sql注入问题
    //可以避免sql拼接
    @Test
    public void login() throws SQLException {
        //String userName = "张三";
        String userName = "随便写\' OR \'1\'=\'1";
        String userPwd = "随便写\' OR \'1\'=\'1";
        String url = "jdbc:mysql://192.168.93.59:3306/day37?characterEncoding=UTF-8";
        String user = "root";
        String password = "123456";
        String driver = "com.mysql.jdbc.Driver";
        Connection connection = DriverManager.getConnection(url,user,password);
        //?为占位符  替代字符串拼接的问题
        String sql = "SELECT * FROM user_info WHERE user_name = ? AND user_pwd = ?";
        //Statement statement = connection.createStatement();
        //此处使用预处理对象替代Statement
        PreparedStatement statement = connection.prepareStatement(sql);
        //填充参数
        statement.setString(1,userName);
        statement.setString(2,userPwd);

        ResultSet set = statement.executeQuery();
        while(set.next()){
            //根据字段结果集中的字段名称取值
            Integer thisuserId = set.getInt("user_id");
            String thisuserName = set.getString("user_name");
            String thisuserPwd = set.getString("user_pwd");
            System.out.println(thisuserId+":"+thisuserName+":"+thisuserPwd);
        }

        //关闭资源
        set.close();
        statement.close();
        connection.close();
    }


    @Test
    public void testSelectAll() throws SQLException {
        List<UserInfo> userInfoList = DBUserInfo.selectAll();
        //此处使用的是什么 JDK8中的方法引用
        userInfoList.forEach(System.out::println);
    }

    @Test
    public void testLogin() throws SQLException {
        UserInfo userInfo = DBUserInfo.login("张三","123");
        System.out.println(userInfo);
    }
}
